package com.xizi.lotterySystem.controller;


import com.xizi.lotterySystem.common.exception.ControllerException;
import com.xizi.lotterySystem.common.exception.errorCode.ControllerErrorCodeException;
import com.xizi.lotterySystem.common.pojo.CommonResult;
import com.xizi.lotterySystem.controller.param.UserMessageLoginParam;
import com.xizi.lotterySystem.controller.param.UserPasswordLoginParam;
import com.xizi.lotterySystem.controller.param.UserRegisterParam;
import com.xizi.lotterySystem.controller.result.CodeEntityResult;
import com.xizi.lotterySystem.controller.result.LoginResult;
import com.xizi.lotterySystem.controller.result.UserBaseInfoResult;
import com.xizi.lotterySystem.controller.result.UserRegisterResult;
import com.xizi.lotterySystem.service.IUserService;
import com.xizi.lotterySystem.service.IVerificationCodeService;
import com.xizi.lotterySystem.service.dto.UserDTO;
import com.xizi.lotterySystem.service.dto.UserRegisterDTO;
import com.xizi.lotterySystem.service.enumerate.UserIdentityEnum;
import com.xizi.lotterySystem.utils.RegexUtil;
import jakarta.mail.internet.MimeMessage;
import jakarta.validation.constraints.NotBlank;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;
import javax.mail.MessagingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;



//用户模块
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private IVerificationCodeService verificationCodeService;

    private static Logger log = LoggerFactory.getLogger(UserController.class);

    /**
     * 注册用户
     *
     * @param userRegisterParam
     * @return
     */
    @PostMapping("/register")
    public CommonResult<UserRegisterResult> register(@RequestBody UserRegisterParam userRegisterParam) {
        log.info("userRegisterParam : {}",userRegisterParam);
        UserRegisterDTO userRegisterDTO = userService.register(userRegisterParam);
        UserRegisterResult result = convertToRegisterResult(userRegisterDTO);
        return CommonResult.success(result);
    }

    /**
     *  发送  QQ邮箱 验证码
     * @param email
     * @return
     */
    @RequestMapping(value = "/verification-code/send",method = RequestMethod.GET)
    public CommonResult sendVerificationCode(@NotBlank(message = "邮箱号不能为空！") String email) {
        log.info("email : {}",email);
        if(!RegexUtil.checkMail(email)){
            throw new ControllerException(ControllerErrorCodeException.MAIL_ERROR);
        }
        verificationCodeService.sendVerificationCode(email);
        return CommonResult.success(true);
    }

    /**
     * 登入： 密码 方式
     * @param param
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/password/login")
    public CommonResult<LoginResult> passwordLogin(@Validated @RequestBody UserPasswordLoginParam param){
        log.info("param : {}",param);

        String token = userService.passwordLogin(param);
        LoginResult loginResult = new LoginResult();
        loginResult.setToken(token);
        loginResult.setIdentity("ADMIN");

        return CommonResult.success(loginResult);
    }

    /**
     * 登入：  QQ邮箱 验证码方式
     * @param param
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "/message/login")
    public CommonResult<LoginResult> messageLogin(@Validated @RequestBody UserMessageLoginParam param){
        log.info("param : {}",param);

        String token = userService.messageLogin(param);
        LoginResult loginResult = new LoginResult();
        loginResult.setToken(token);
        loginResult.setIdentity("ADMIN");

        return CommonResult.success(loginResult);
    }

    /**
     * 查询 用户列表
     * @param identity  可通过转入的  identity 值
     *                  自用返回用户列表， 如为null 则放回所以用户信息
     * @return
     */
    @GetMapping(value = "/base-user/find-list")
    public CommonResult<List<UserBaseInfoResult>> findList(String identity){
        List<UserDTO> userDTOList = null;
        log.info("identity : {}",identity);
        if(identity == null){
            userDTOList = userService.findUserList(null);
        }else{
            userDTOList = userService.findUserList(UserIdentityEnum.getByValue(identity));
        }

        return CommonResult.success(convertToBaseInfoResultList(userDTOList));
    }

    // dto  ->   返回对象
    private List<UserBaseInfoResult> convertToBaseInfoResultList(List<UserDTO> userDTOList) {
        List<UserBaseInfoResult> ret = new ArrayList<UserBaseInfoResult>();
        for (UserDTO u : userDTOList) {
            UserBaseInfoResult userBaseInfoResult = new UserBaseInfoResult();
            userBaseInfoResult.setUserId(u.getId());
            userBaseInfoResult.setUserName(u.getUserName());
            userBaseInfoResult.setIdentity(u.getIdentity());
            ret.add(userBaseInfoResult);
        }
        return ret;
    }

    // dto  ->   返回对象
    private UserRegisterResult convertToRegisterResult(UserRegisterDTO userRegisterDTO) {
        UserRegisterResult result = new UserRegisterResult();
        result.setUserId(userRegisterDTO.getId());
        return result;
    }

























    @Autowired
    private JavaMailSender javaMailSender;

    //读取yml文件中username的值并赋值给form
    @Value("${spring.mail.username}")
    private String from;

    @RequestMapping("/login/sendEmail")
    public CodeEntityResult sendSimpleMail(@RequestParam(value = "emailReceiver") String emailReceiver) throws MessagingException, jakarta.mail.MessagingException {
        log.info("emailReceiver : {}",emailReceiver);

        EmailEngine emailEngine = new EmailEngine();
        // 构建一个邮件对象
//        SimpleMailMessage message = new SimpleMailMessage();
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        //返回给前端的code-json module
        CodeEntityResult codeEntity = new CodeEntityResult();
        // 设置邮件发送者
        helper.setFrom(from);
        // 设置邮件接收者
        helper.setTo(emailReceiver);
        // 设置邮件的主题
        helper.setSubject("注册验证码");
        // 设置邮件的正文
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int r = random.nextInt(10);
            code.append(r);
        }
        String text = emailEngine.buildContent(code.toString());
        helper.setText(text,true);
        // 发送邮件
        try {
            javaMailSender.send(message);
            codeEntity.setCode(code.toString());
            codeEntity.setMsg("success");
            return codeEntity;
        } catch (MailException e) {
            e.printStackTrace();
        }
        codeEntity.setCode("null");
        codeEntity.setMsg("fail");
        return codeEntity;
    }


}
